<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Java中equals与hashCode的关系解析</title>
    <link rel="stylesheet" href="https://cdn.staticfile.org/font-awesome/6.4.0/css/all.min.css">
    <link rel="stylesheet" href="https://cdn.staticfile.org/tailwindcss/2.2.19/tailwind.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Noto+Serif+SC:wght@400;500;600;700&family=Noto+Sans+SC:wght@300;400;500;700&display=swap" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/mermaid@latest/dist/mermaid.min.js"></script>
    <style>
        body {
            font-family: 'Noto Sans SC', Tahoma, Arial, Roboto, "Droid Sans", "Helvetica Neue", "Droid Sans Fallback", "Heiti SC", "Hiragino Sans GB", Simsun, sans-serif;
            background-color: #f8f9fa;
            color: #333;
            line-height: 1.6;
        }
        h1, h2, h3, h4, h5 {
            font-family: 'Noto Serif SC', serif;
        }
        .hero {
            background: linear-gradient(135deg, #6e8efb 0%, #a777e3 100%);
            color: white;
        }
        .card {
            transition: transform 0.3s ease, box-shadow 0.3s ease;
        }
        .card:hover {
            transform: translateY(-5px);
            box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
        }
        .code-block {
            background-color: #282c34;
            border-radius: 8px;
            color: #abb2bf;
        }
        .important-note {
            border-left: 4px solid #4f46e5;
            background-color: #eef2ff;
        }
        .footer {
            background-color: #1a1a1a;
            color: #e5e7eb;
        }
        .footer a:hover {
            color: #a5b4fc;
        }
    </style>
</head>
<body>
    <!-- Hero Section -->
    <section class="hero py-20 px-4 md:py-28 md:px-6 lg:px-8">
        <div class="max-w-4xl mx-auto text-center">
            <h1 class="text-4xl md:text-5xl lg:text-6xl font-bold mb-6 animate-fade-in-down">深入理解Java中的equals与hashCode</h1>
            <p class="text-xl md:text-2xl opacity-90 mb-8">为什么重写equals时必须重写hashCode？</p>
            <div class="flex justify-center space-x-4">
                <span class="inline-flex items-center px-3 py-1 rounded-full bg-white bg-opacity-20 text-sm font-medium">
                    <i class="fas fa-code mr-2"></i>Java基础
                </span>
                <span class="inline-flex items-center px-3 py-1 rounded-full bg-white bg-opacity-20 text-sm font-medium">
                    <i class="fas fa-layer-group mr-2"></i>集合框架
                </span>
            </div>
        </div>
    </section>

    <!-- Main Content -->
    <main class="max-w-4xl mx-auto px-4 py-12 sm:px-6 lg:px-8">
        <!-- Introduction -->
        <section class="mb-16">
            <p class="text-lg text-gray-700 mb-6 leading-relaxed">
                在Java编程中，<code class="bg-gray-100 px-1 py-0.5 rounded">equals</code>和<code class="bg-gray-100 px-1 py-0.5 rounded">hashCode</code>是两个基础但至关重要的方法。理解它们之间的关系对于编写正确和高效的Java代码至关重要，特别是在使用集合框架时。
            </p>
            
            <!-- Visualization -->
            <div class="my-10 bg-white rounded-xl shadow-md overflow-hidden p-6">
                <div class="mermaid">
                    graph LR
                    A[重写equals方法] --> B[必须重写hashCode]
                    B --> C[遵守通用约定]
                    C --> D[保证哈希集合正确工作]
                    D --> E[避免数据丢失]
                    D --> F[确保查找正确性]
                </div>
            </div>
        </section>

        <!-- Section 1 -->
        <section class="mb-16">
            <div class="flex items-center mb-6">
                <div class="w-10 h-10 rounded-full bg-indigo-100 flex items-center justify-center mr-4">
                    <span class="text-indigo-600 font-bold">1</span>
                </div>
                <h2 class="text-2xl font-bold text-gray-800">hashCode的基本概念</h2>
            </div>
            <div class="pl-14">
                <div class="card bg-white rounded-lg shadow-sm p-6 mb-6">
                    <p class="text-gray-700 mb-4">
                        <code class="bg-gray-100 px-1 py-0.5 rounded">hashCode</code>方法返回一个整数，作为对象的哈希码。Java集合（如<code class="bg-gray-100 px-1 py-0.5 rounded">HashSet</code>, <code class="bg-gray-100 px-1 py-0.5 rounded">HashMap</code>）使用哈希码来快速查找对象。哈希码用于确定对象在哈希表中的位置，以提高查找效率。
                    </p>
                    <div class="bg-gray-50 p-4 rounded-lg mt-4">
                        <p class="text-sm text-gray-600 flex items-start">
                            <i class="fas fa-info-circle text-indigo-500 mr-2 mt-1"></i>
                            <span>哈希码就像是对象的"数字指纹"，虽然不同对象可能有相同的哈希码（哈希冲突），但相同的对象必须返回相同的哈希码。</span>
                        </p>
                    </div>
                </div>
            </div>
        </section>

        <!-- Section 2 -->
        <section class="mb-16">
            <div class="flex items-center mb-6">
                <div class="w-10 h-10 rounded-full bg-indigo-100 flex items-center justify-center mr-4">
                    <span class="text-indigo-600 font-bold">2</span>
                </div>
                <h2 class="text-2xl font-bold text-gray-800">equals与hashCode的关系</h2>
            </div>
            <div class="pl-14">
                <div class="card bg-white rounded-lg shadow-sm p-6 mb-6">
                    <p class="text-gray-700 mb-4">
                        根据Java的约定，如果两个对象通过<code class="bg-gray-100 px-1 py-0.5 rounded">equals</code>方法比较相等，那么这两个对象必须返回相同的<code class="bg-gray-100 px-1 py-0.5 rounded">hashCode</code>。这条约定在Java文档中明确规定，确保了在使用基于哈希的集合时的一致性。
                    </p>
                    
                    <div class="mt-6 grid md:grid-cols-2 gap-6">
                        <div class="important-note p-4 rounded-lg">
                            <h3 class="font-semibold text-indigo-700 mb-2 flex items-center">
                                <i class="fas fa-check-circle mr-2"></i>必须遵守的约定
                            </h3>
                            <ul class="list-disc pl-5 text-gray-700 space-y-1">
                                <li>相等的对象必须有相同的哈希码</li>
                                <li>不相等的对象可以有相同哈希码（哈希冲突）</li>
                                <li>哈希码应该在对象生命周期内保持不变</li>
                            </ul>
                        </div>
                        
                        <div class="bg-amber-50 p-4 rounded-lg">
                            <h3 class="font-semibold text-amber-700 mb-2 flex items-center">
                                <i class="fas fa-exclamation-triangle mr-2"></i>违反后果
                            </h3>
                            <ul class="list-disc pl-5 text-gray-700 space-y-1">
                                <li>哈希集合无法正确工作</li>
                                <li>可能导致数据丢失</li>
                                <li>查找结果不一致</li>
                            </ul>
                        </div>
                    </div>
                </div>
            </div>
        </section>

        <!-- Section 3 -->
        <section class="mb-16">
            <div class="flex items-center mb-6">
                <div class="w-10 h-10 rounded-full bg-indigo-100 flex items-center justify-center mr-4">
                    <span class="text-indigo-600 font-bold">3</span>
                </div>
                <h2 class="text-2xl font-bold text-gray-800">为什么重写hashCode</h2>
            </div>
            <div class="pl-14">
                <div class="card bg-white rounded-lg shadow-sm p-6">
                    <div class="grid md:grid-cols-2 gap-8">
                        <div>
                            <h3 class="text-xl font-semibold text-gray-800 mb-4 flex items-center">
                                <i class="fas fa-shield-alt text-indigo-500 mr-3"></i>避免数据丢失
                            </h3>
                            <p class="text-gray-700">
                                如果重写了<code class="bg-gray-100 px-1 py-0.5 rounded">equals</code>而未重写<code class="bg-gray-100 px-1 py-0.5 rounded">hashCode</code>，当两个对象被认为相等时，它们的哈希码可能不同，这可能导致集合（如<code class="bg-gray-100 px-1 py-0.5 rounded">HashSet</code>或<code class="bg-gray-100 px-1 py-0.5 rounded">HashMap</code>）无法正确找到、存储或检索这些对象，从而引发数据丢失。
                            </p>
                        </div>
                        
                        <div>
                            <h3 class="text-xl font-semibold text-gray-800 mb-4 flex items-center">
                                <i class="fas fa-cogs text-indigo-500 mr-3"></i>确保集合操作正确性
                            </h3>
                            <p class="text-gray-700">
                                当你将对象放入哈希集合中时，集合会使用<code class="bg-gray-100 px-1 py-0.5 rounded">hashCode</code>来确定对象的位置。如果对象的哈希码不一致，即使对象被认为相等，它们可能会被存储在不同的位置，从而导致查找、更新或删除时出现问题。
                            </p>
                        </div>
                    </div>
                </div>
            </div>
        </section>

        <!-- Section 4 -->
        <section class="mb-16">
            <div class="flex items-center mb-6">
                <div class="w-10 h-10 rounded-full bg-indigo-100 flex items-center justify-center mr-4">
                    <span class="text-indigo-600 font-bold">4</span>
                </div>
                <h2 class="text-2xl font-bold text-gray-800">代码示例</h2>
            </div>
            <div class="pl-14">
                <div class="card bg-white rounded-lg shadow-sm overflow-hidden">
                    <div class="bg-gray-900 px-4 py-3 flex items-center">
                        <div class="flex space-x-2 mr-4">
                            <span class="w-3 h-3 rounded-full bg-red-500"></span>
                            <span class="w-3 h-3 rounded-full bg-yellow-500"></span>
                            <span class="w-3 h-3 rounded-full bg-green-500"></span>
                        </div>
                        <span class="text-gray-300 text-sm">Person.java</span>
                    </div>
                    <div class="code-block p-4 overflow-x-auto">
                        <pre><code class="text-sm">public class Person {
    private String name;
    private int age;

    // Constructor, getters, and setters

    @Override
    public boolean equals(Object obj) {
        if (this == obj) return true;
        if (!(obj instanceof Person)) return false;
        Person other = (Person) obj;
        return this.name.equals(other.name) && this.age == other.age;
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, age);
    }
}</code></pre>
                    </div>
                    <div class="p-4 bg-gray-50 border-t border-gray-200">
                        <p class="text-gray-600 text-sm">
                            <i class="fas fa-code text-indigo-500 mr-2"></i>在这个例子中，如果我们只重写了<code class="bg-gray-200 px-1 py-0.5 rounded">equals</code>方法而不重写<code class="bg-gray-200 px-1 py-0.5 rounded">hashCode</code>，相同名称和年龄的<code class="bg-gray-200 px-1 py-0.5 rounded">Person</code>对象在哈希集合中会被视为不同的对象，这将导致意外的行为，如无法从集合中检索到这些对象。
                        </p>
                    </div>
                </div>
            </div>
        </section>

        <!-- Section 5 -->
        <section class="mb-16">
            <div class="flex items-center mb-6">
                <div class="w-10 h-10 rounded-full bg-indigo-100 flex items-center justify-center mr-4">
                    <span class="text-indigo-600 font-bold">5</span>
                </div>
                <h2 class="text-2xl font-bold text-gray-800">实践建议</h2>
            </div>
            <div class="pl-14">
                <div class="grid md:grid-cols-2 gap-6">
                    <div class="card bg-white rounded-lg shadow-sm p-6">
                        <h3 class="text-xl font-semibold text-gray-800 mb-4 flex items-center">
                            <i class="fas fa-check-double text-indigo-500 mr-3"></i>始终遵循约定
                        </h3>
                        <p class="text-gray-700 mb-4">
                            在重写<code class="bg-gray-100 px-1 py-0.5 rounded">equals</code>时，应该总是重写<code class="bg-gray-100 px-1 py-0.5 rounded">hashCode</code>，以保证遵循Java的合同。
                        </p>
                        <p class="text-gray-700">
                            一致性：确保<code class="bg-gray-100 px-1 py-0.5 rounded">hashCode</code>和<code class="bg-gray-100 px-1 py-0.5 rounded">equals</code>的实现逻辑一致，即相等的对象应有相同的哈希码。
                        </p>
                    </div>
                    
                    <div class="card bg-white rounded-lg shadow-sm p-6">
                        <h3 class="text-xl font-semibold text-gray-800 mb-4 flex items-center">
                            <i class="fas fa-tachometer-alt text-indigo-500 mr-3"></i>性能考量
                        </h3>
                        <p class="text-gray-700 mb-4">
                            虽然重写<code class="bg-gray-100 px-1 py-0.5 rounded">hashCode</code>可能引入一定的性能开销，但合理的哈希实现会提升哈希集合的查询性能，因此合理设计<code class="bg-gray-100 px-1 py-0.5 rounded">hashCode</code>方法是非常重要的。
                        </p>
                        <div class="bg-blue-50 p-3 rounded-lg">
                            <p class="text-sm text-blue-700">
                                <i class="fas fa-lightbulb text-blue-500 mr-2"></i>使用<code class="bg-blue-100 px-1 py-0.5 rounded">Objects.hash()</code>可以简化哈希码的计算并降低出错概率。
                            </p>
                        </div>
                    </div>
                </div>
            </div>
        </section>

        <!-- Summary -->
        <section class="bg-indigo-50 rounded-xl p-8 mb-16">
            <h2 class="text-2xl font-bold text-indigo-800 mb-6 flex items-center">
                <i class="fas fa-clipboard-check text-indigo-600 mr-3"></i>核心要点总结
            </h2>
            <ol class="space-y-4 text-gray-700">
                <li class="flex items-start">
                    <span class="bg-indigo-100 text-indigo-800 rounded-full w-6 h-6 flex items-center justify-center mr-3 flex-shrink-0">1</span>
                    <span>重写<code class="bg-indigo-100 px-1 py-0.5 rounded">equals</code>时必须重写<code class="bg-indigo-100 px-1 py-0.5 rounded">hashCode</code>以遵守Java合同</span>
                </li>
                <li class="flex items-start">
                    <span class="bg-indigo-100 text-indigo-800 rounded-full w-6 h-6 flex items-center justify-center mr-3 flex-shrink-0">2</span>
                    <span>相等的对象必须产生相同的哈希码，这是哈希集合正确工作的基础</span>
                </li>
                <li class="flex items-start">
                    <span class="bg-indigo-100 text-indigo-800 rounded-full w-6 h-6 flex items-center justify-center mr-3 flex-shrink-0">3</span>
                    <span>使用<code class="bg-indigo-100 px-1 py-0.5 rounded">Objects.hash()</code>可以简化哈希码计算并减少错误</span>
                </li>
                <li class="flex items-start">
                    <span class="bg-indigo-100 text-indigo-800 rounded-full w-6 h-6 flex items-center justify-center mr-3 flex-shrink-0">4</span>
                    <span>良好的<code class="bg-indigo-100 px-1 py-0.5 rounded">hashCode</code>实现能提升哈希集合的性能</span>
                </li>
            </ol>
        </section>
    </main>

    <!-- Footer -->
    <footer class="footer py-8 px-4">
        <div class="max-w-4xl mx-auto">
            <div class="flex flex-col md:flex-row justify-between items-center">
                <div class="mb-4 md:mb-0">
                    <p class="text-sm">技术小馆</p>
                </div>
                <div>
                    <a href="http://www.yuque.com/jtostring" class="text-sm hover:underline transition-colors duration-200">
                        <i class="fas fa-globe mr-2"></i>http://www.yuque.com/jtostring
                    </a>
                </div>
            </div>
        </div>
    </footer>

    <script>
        mermaid.initialize({
            startOnLoad: true,
            theme: 'default',
            flowchart: {
                useMaxWidth: true,
                htmlLabels: true,
                curve: 'basis'
            }
        });
    </script>
</body>
</html>